import sys
from linkkit import linkkit
import threading
import os
import time
import datetime
import logging

# config log
ROOT = '/home/court/project'

class mqtt:

    def __init__(self):
        
        __log_format = '%(asctime)s-%(process)d-%(thread)d - %(name)s:%(module)s:%(funcName)s - %(levelname)s - %(message)s'
        logging.basicConfig(format=__log_format)

        self.lk = linkkit.LinkKit(
            host_name="cn-shanghai",
            product_key="k0et1KZjgdv",
            device_name="ES-0001",
            device_secret="3e1f1ddeba65fcd514d2041124c03859")
        self.lk.enable_logger(logging.DEBUG)
        self._init_callback_function()
        self.rpcc_msg = ''
        self.id = ''

    def on_device_dynamic_register(self,rc, value, userdata):
        if rc == 0:
            print("dynamic register device success, value:" + value)
        else:
            print("dynamic register device fail, message:" + value)


    def on_connect(self,session_flag, rc, userdata):
        print("on_connect:%d,rc:%d" % (session_flag, rc))
        self.lk.subscribe_rrpc_topic(self.lk.to_full_topic("user/get"))
        pass


    def on_disconnect(self,rc, userdata):
        print("on_disconnect:rc:%d,userdata:" % rc)


    def on_topic_message(self,topic, payload, qos, userdata):
        print("on_topic_message:" + topic + " payload:" + str(payload) + " qos:" + str(qos))
        pass


    def on_subscribe_topic(self,mid, granted_qos, userdata):
        print("on_subscribe_topic mid:%d, granted_qos:%s" %
            (mid, str(','.join('%s' % it for it in granted_qos))))
        pass


    def on_unsubscribe_topic(self,mid, userdata):
        print("on_unsubscribe_topic mid:%d" % mid)
        pass


    def on_publish_topic(self,mid, userdata):
        print("on_publish_topic mid:%d" % mid)


    def on_topic_rrpc_message(self, id, topic, payload, qos, userdata):
        self.id = id
        self.rpcc_msg = payload
        ss = "on_topic_rrpc_message: id:%s, topic:%s, payload:%s" % (id, topic, payload)
        print(ss)
        # 业务逻辑
        now = str(datetime.datetime.now())
        ss = now+': '+ss+'\n'
        with open(ROOT+'/logs/rrpc_log.txt','a') as f:
            f.write(ss)
        f.close()
        
    def response_rrpc(self,msg):
        self.lk.thing_answer_rrpc(self.id, msg)   


    def on_thing_call_service(self,identifier, request_id, params, userdata):
        print("on_thing_call_service: identifier:%s, request_id:%s, params:%s" % (identifier, request_id, params))
        ...
        self.lk.thing_answer_service(identifier, request_id, 200, {}) 


    def _init_callback_function(self,):
        self.lk.on_device_dynamic_register = self.on_device_dynamic_register
        self.lk.on_connect = self.on_connect
        self.lk.on_disconnect = self.on_disconnect
        self.lk.on_topic_message = self.on_topic_message
        self.lk.on_subscribe_topic = self.on_subscribe_topic
        self.lk.on_unsubscribe_topic = self.on_unsubscribe_topic
        self.lk.on_publish_topic = self.on_publish_topic
        self.lk.on_topic_rrpc_message = self.on_topic_rrpc_message
        self.lk.on_thing_call_service = self.on_thing_call_service

        self.lk.config_device_info("Eth|03ACDEFF0032|Eth|03ACDEFF0031")
        self.lk.connect_async()
        self.lk.start_worker_loop()
        
# mt = mqtt()

# while True:
#     try:
#         msg = input()
#     except KeyboardInterrupt:
#         sys.exit()
#     else:
#         if msg == "1":
#             mt.lk.disconnect()
#         elif msg == "2":
#             mt.lk.connect_async()
#         elif msg == "3":
#             rc, mid = mt.lk.subscribe_topic(mt.lk.to_full_topic("user/get"))
#             if rc == 0:
#                 print("subscribe topic success:%r, mid:%r" % (rc, mid))
#             else:
#                 print("subscribe topic fail:%d" % rc)
#         elif msg == "4":
#             rc, mid = mt.lk.unsubscribe_topic(mt.lk.to_full_topic("user/get"))
#             if rc == 0:
#                 print("unsubscribe topic success:%r, mid:%r" % (rc, mid))
#             else:
#                 print("unsubscribe topic fail:%d" % rc)
#         elif msg == "5":
#             rc, mid = mt.lk.publish_topic(mt.lk.to_full_topic("user/update"), "update")
#             if rc == 0:
#                 print("publish topic success:%r, mid:%r" % (rc, mid))
#             else:
#                 print("publish topic fail:%d" % rc)
#         elif msg == "6":
#             rc, mid = mt.lk.subscribe_topic([(mt.lk.to_full_topic("user/test2"), 1),
#                                           (mt.lk.to_full_topic("user/test"), 1),
#                                           (mt.lk.to_full_topic("user/sub"), 1)])
#             if rc == 0:
#                 print("subscribe multiple topics success:%r, mid:%r" % (rc, mid))
#             else:
#                 print("subscribe multiple topics fail:%d" % rc)
#         elif msg == "7":
#             rc, mid = mt.lk.unsubscribe_topic([mt.lk.to_full_topic("user/test2"), mt.lk.to_full_topic("user/test")])
#             if rc == 0:
#                 print("unsubscribe multiple topics success:%r, mid:%r" % (rc, mid))
#             else:
#                 print("unsubscribe multiple topics fail:%d" % rc)
#         elif msg == "8":
#             ret = mt.lk.dump_user_topics()
#             print("user topics:%s", str(ret))
#         elif msg == "9":
#             mt.lk.destruct()
#             print("destructed")
        

#         else:
#             sys.exit()
